package com.yiwei.hdb.activity;

import android.annotation.TargetApi;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yiwei.hdb.R;
import com.yiwei.hdb.api.Api;
import com.yiwei.hdb.api.bean.XueXinRegisterSubmitBean;
import com.yiwei.hdb.api.bean.XueXinRegisterV3Bean;
import com.yiwei.hdb.event.XueXinQuestionEvent;
import com.yiwei.hdb.util.ImageUtil;
import com.yiwei.hdb.util.Network;
import com.yiwei.hdb.util.RxLifeUtil;
import com.yiwei.hdb.util.Spans;
import com.yiwei.hdb.util.ToastUtil;
import com.yiwei.hdb.util.UI;
import com.yiwei.hdb.util.Util;
import com.yiwei.hdb.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/6/10.
 */

public class V3XueXinRegisterActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.txt_pass)
    TextView txtPass;
    @BindView(R.id.edit_pass)
    EditText editPass;
    @BindView(R.id.txt_repass)
    TextView txtRepass;
    @BindView(R.id.edit_repass)
    EditText editRepass;
    @BindView(R.id.txt_name)
    TextView txtName;
    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.txt_idno)
    TextView txtIdno;
    @BindView(R.id.edit_idno)
    EditText editIdno;
    @BindView(R.id.txt_email)
    TextView txtEmail;
    @BindView(R.id.edit_email)
    EditText editEmail;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.edit_image_code)
    EditText editImageCode;
    @BindView(R.id.img_code)
    ImageView imgCode;
    @BindView(R.id.code_view)
    LinearLayout codeView;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.btn_send_code)
    TextView btnSendCode;
    @BindView(R.id.edit_mibao)
    TextView editMibao;
    @BindView(R.id.btn_mibao)
    LinearLayout btnMibao;
    @BindView(R.id.txt_phone)
    TextView txtPhone;
    @BindView(R.id.txt_img_code)
    TextView txtImgCode;
    @BindView(R.id.txt_code)
    TextView txtCode;
    private Unbinder unbinder;
    private int x30;
    private XueXinQuestionEvent event;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xuexin_register_v3);
        initBar();
        unbinder = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            try {
                btnSendCode.setEnabled(false);
                btnSendCode.setText((millisUntilFinished / 1000) + getResources().getString(R.string.resend));
//                btnSendCode.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray));
            } catch (Resources.NotFoundException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFinish() {
            resetBtn();
        }
    };


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        btnSendCode.setEnabled(true);
        btnSendCode.setText(getResources().getString(R.string.send_code_again));
//        btnSendCode.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.blue));
    }

    private Spanned setLeftTextData(String text) {
        return Spans.with(this).font("*", x30, 0xffFE5A59).
                font(text, x30, 0xff27293E).
                build();
    }

    private void init() {

        x30 = getResources().getDimensionPixelSize(R.dimen.x30);
        txtTitle.setText("学信网注册");
        txtPhone.setText(setLeftTextData("手机号"));
        txtImgCode.setText(setLeftTextData("图形验证码"));
        txtCode.setText(setLeftTextData("短信验证码"));
        txtPass.setText(setLeftTextData("密码"));
        txtRepass.setText(setLeftTextData("密码确认"));
        txtName.setText(setLeftTextData("姓名"));
        txtIdno.setText(setLeftTextData("证件号码"));
        getChsiImgCodeInfo();
    }

    @OnTextChanged({R.id.edit_phone, R.id.edit_image_code, R.id.edit_code, R.id.edit_pass, R.id.edit_repass, R.id.edit_name, R.id.edit_idno})
    void afterTextChanged(Editable s) {
        if (!TextUtils.isEmpty(UI.toString(editPhone)) && !TextUtils.isEmpty(UI.toString(editImageCode)) && !TextUtils.isEmpty(UI.toString(editCode)) && !TextUtils.isEmpty(UI.toString(editPass)) && !TextUtils.isEmpty(UI.toString(editRepass)) && !TextUtils.isEmpty(UI.toString(editName)) && !TextUtils.isEmpty(UI.toString(editIdno))) {
            btnSubmit.setSelected(true);
        } else {
            btnSubmit.setSelected(false);
        }
    }

    public void getXueXinRegister(String password, String password_confirmation, String realname, String idno, String email) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        XueXinRegisterSubmitBean bean = new XueXinRegisterSubmitBean();
        bean.mobile = UI.toString(editPhone);

        bean.password = password;
        bean.password_confirmation = password_confirmation;
        bean.realname = realname;
        bean.idno = idno;
        bean.email = email;
        bean.vcode = UI.toString(editCode);
        bean.credentialtype = "SFZ";
        if (!TextUtils.isEmpty(UI.toString(editEmail))) {
            bean.email = UI.toString(editEmail);
        }
        if (event != null) {
            bean.pwdreq1 = event.pwdreq1;
            bean.pwdreq2 = event.pwdreq2;
            bean.pwdreq3 = event.pwdreq3;
            bean.pwdanswer1 = event.pwdanswer1;
            bean.pwdanswer2 = event.pwdanswer2;
            bean.pwdanswer3 = event.pwdanswer3;
        }

        Api.api_service.getXueXinRegisterV3(bean).compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(model -> {
                    if (model.getStatus() == 1) {
                        ToastUtil.makeText(this, "注册成功");
                        finish();
                    } else {
                        ToastUtil.makeText(this, model.getMsg());
                    }

                });
    }


    public void getChsiImgCodeInfo() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败");
            return;
        }

        Api.api_service.getXueXinCode().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(model -> {
                    String imgStr = "";
                    String captcha = model.data;
                    if (captcha.contains(",")) {
                        imgStr = captcha.substring(captcha.indexOf(',') + 1);
                        imgCode.setImageBitmap(ImageUtil.stringtoBitmap(imgStr));
                    } else imgCode.setImageDrawable(null);
                });
    }

    public void getXueXinRegisterSMSV3(String mobile, String captcha) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        XueXinRegisterV3Bean bean = new XueXinRegisterV3Bean();
        bean.captcha = captcha;
        bean.mobile = mobile;
        Api.api_service.getXueXinRegisterSMSV3(bean).compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(model -> {
                    if (model.getStatus() == 1) {
                        timer.start();
                        ToastUtil.makeText(this, "短信已发送，请注意查收");
                    } else {
                        ToastUtil.makeText(this, model.getMsg());
                        getChsiImgCodeInfo();
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSelectMoney(XueXinQuestionEvent msg) {
        editMibao.setText("已设置");
        event = msg;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
        unbinder = null;
    }

    @OnClick({R.id.btn_mibao, R.id.img_code, R.id.btn_send_code, R.id.btn_back, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_mibao:
                Util.startActivity(this, V3XueXinQuestionSetActivity.class);
                break;
            case R.id.img_code:
                getChsiImgCodeInfo();
                break;
            case R.id.btn_send_code:
                if (checkImageCode()) {
                    try {
                        getXueXinRegisterSMSV3(UI.toString(editPhone), URLEncoder.encode(editImageCode.getText().toString(), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                break;

            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_submit:
                if (codeViewInputCheck()) {
                    getXueXinRegister(UI.toString(editPass), UI.toString(editRepass), UI.toString(editName), UI.toString(editIdno), UI.toString(editEmail));
                }

                break;
        }
    }

    private boolean checkImageCode() {
        if (TextUtils.isEmpty(UI.toString(editPhone))) {
            ToastUtil.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT);
            return false;
        }
        if (TextUtils.isEmpty(UI.toString(editImageCode))) {
            ToastUtil.makeText(this, "图片验证码不能为空", Toast.LENGTH_SHORT);
            return false;
        }
        return true;
    }

    private boolean codeViewInputCheck() {
        if (TextUtils.isEmpty(UI.toString(editPhone))) {
            ToastUtil.makeText(getApplicationContext(), "手机号不能为空", Toast.LENGTH_SHORT);
            return false;
        }
        if (TextUtils.isEmpty(UI.toString(editImageCode))) {
            ToastUtil.makeText(getApplicationContext(), "图形验证码不能为空", Toast.LENGTH_SHORT);
            return false;
        }
        if (TextUtils.isEmpty(UI.toString(editCode))) {
            ToastUtil.makeText(getApplicationContext(), "短信验证码不能为空", Toast.LENGTH_SHORT);
            return false;
        }
        if (TextUtils.isEmpty(UI.toString(editPass))) {
            ToastUtil.makeText(getApplicationContext(), "密码不能为空", Toast.LENGTH_SHORT);
            return false;
        }
        if (TextUtils.isEmpty(UI.toString(editRepass))) {
            ToastUtil.makeText(getApplicationContext(), "确认密码不能为空", Toast.LENGTH_SHORT);
            return false;
        }
        if (TextUtils.isEmpty(UI.toString(editName))) {
            ToastUtil.makeText(getApplicationContext(), "姓名不能为空", Toast.LENGTH_SHORT);
            return false;
        }
        if (TextUtils.isEmpty(UI.toString(editIdno))) {
            ToastUtil.makeText(getApplicationContext(), "证件号码不能为空", Toast.LENGTH_SHORT);
            return false;
        }
        return true;
    }


}
